import ctypes
import json
import os


class SpectrometerController():
	def __init__(self):
		# 加载libusb.so和libseabreeze.so动态链接库
		self.libusb_handle = ctypes.CDLL("./libs/seabreeze_sdk/USB_Control_X64.dll")
		self.libseabreeze_handle = ctypes.CDLL("./libs/seabreeze_sdk/SeaBreeze.dll")

		# 函数原型
		self.seabreeze_open_spectrometer = self.load_function("seabreeze_open_spectrometer")#打开光谱仪
		self.seabreeze_close_spectrometer = self.load_function("seabreeze_close_spectrometer")#关闭光谱仪
		#self.seabreeze_get_modle = self.load_function("seabreeze_get_modle")#获取光谱仪型号
		self.seabreeze_set_integration_time_microsec = self.load_function("seabreeze_set_integration_time_microsec")#设置积分时间，注意是微秒
		self.seabreeze_get_formatted_spectrum = self.load_function("seabreeze_get_formatted_spectrum")#获取光谱
		self.seabreeze_get_wavelengths = self.load_function("seabreeze_get_wavelengths")#获取波长
		self.seabreeze_get_serial_number = self.load_function("seabreeze_get_serial_number")#获取光谱仪序列号
		#self.seabreeze_open_all_spectrometers = self.load_function("seabreeze_open_all_spectrometers")
		self.seabreeze_set_laser_switch = self.load_function("seabreeze_set_laser_switch")#设置激光开关，0是关闭，1是打开
		self.seabreeze_set_laser_power = self.load_function("seabreeze_set_laser_power")#设置功率
		self.seabreeze_set_average = self.load_function("seabreeze_set_average")#设置平均次数
		self.seabreeze_get_laser_power = self.load_function("seabreeze_get_laser_power") #获取功率


	def load_function(self, function_name):
		# 获取函数指针并设置参数类型
		func = getattr(self.libseabreeze_handle, function_name)
		func.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
		return func

	def print_modle(self):
		err = ctypes.c_int(-1)
		print("开始获取光谱仪序列号")
		serial_num = self.seabreeze_get_serial_number(0,err)
		print(f"光谱仪序列号是：{serial_num}")
		#为0则没有找到，其他为找到
		if serial_num == 0:
			return True
		else:
			return False

	def start_and_set(self,power, integration_time, average_times):
		err = ctypes.c_int(-1)
		# 打开光谱仪
		self.seabreeze_open_spectrometer(0, ctypes.byref(err))
		self.print_modle()
		# 设置积分时间
		print(f"设置积分时间：{integration_time*1000}")
		self.seabreeze_set_integration_time_microsec(0, ctypes.byref(err), int(integration_time) * 1000)
		# 设置平均次数
		print(f"设置平均次数：{average_times}")
		self.seabreeze_set_average(0, ctypes.byref(err), int(average_times))
		# 打开激光并设置激光功率
		print(f"设置激光功率：{power}")
		self.seabreeze_set_laser_switch(0, ctypes.byref(err), 1)
		self.seabreeze_set_laser_power(0, ctypes.byref(err), int(power))

	def close_laser_switch(self):
		err = ctypes.c_int(-1)
		# 关闭激光
		self.seabreeze_set_laser_switch(0, ctypes.byref(err), 0)

	def cease_spec(self):
		err = ctypes.c_int(-1)
		# 关闭激光和光谱仪
		self.seabreeze_set_laser_switch(0, ctypes.byref(err), 0)
		self.seabreeze_close_spectrometer(0, ctypes.byref(err))
		print("关闭")

	def run_sp(self):
		err = ctypes.c_int(-1)
		# 获取波长
		wave_lengths = (ctypes.c_double * 2048)()
		self.seabreeze_get_wavelengths(0,  ctypes.byref(err), wave_lengths, 2048)
		wave_lengths_list = list(wave_lengths)

		# 获取光信号
		light_signal = (ctypes.c_double * 2048)()
		self.seabreeze_get_formatted_spectrum(0, ctypes.byref(err), light_signal, 2048)
		light_signal_list = list(light_signal)

		# 计算结果并输出
		# result = [(light_signal[i] - signal[i]) for i in range(2048)]
		# for i in range(2048):
		# 	print(result[i])

		# print(wave_lengths_list)
		# print(light_signal_list)
		return wave_lengths_list, light_signal_list

		# 如果需要，可以继续调用其他函数

if __name__ == "__main__":
	err = ctypes.c_int(-1)
	spectrometer = SpectrometerController()
	spectrometer.start_and_set(450,1000,1)
	listx, listy = spectrometer.run_sp()
	print(listy)
	spectrometer.cease_spec()

	# # 把这个index作为命名放入temp文件夹里
	# # 将数据保存到JSON文件
	# data = {"index": 1, "listx": listx, "listy": listy}
	# json_data = json.dumps(data)
	# # 创建temp文件夹（如果不存在）
	# temp_folder = "F:\\pythonProject\\SpectrometerControlPlatform\\data\\temp"
	# os.makedirs(temp_folder, exist_ok=True)
	# # 构建文件名并保存JSON文件
	# filename = os.path.join(temp_folder, f"data_{1}.json")
	# with open(filename, "w") as json_file:
	# 	json_file.write(json_data)
